﻿using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;

namespace MatrixWebApiCore.Filter
{
    /// <summary>
    /// header中添加自定义token验证
    /// </summary>
    public class HeaderTokenFilter : IOperationFilter
    { 
        public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context)
        {
            bool _actionAttributes = context.ApiDescription.ActionAttributes().Any(a => a.GetType() == typeof(TokenFilter));
            if (!_actionAttributes)
            {
                _actionAttributes = context.ApiDescription.ControllerAttributes().Any(a => a.GetType() == typeof(TokenFilter));
            }
            var isAllowAnonymous = context.ApiDescription.ActionAttributes().Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
            if (_actionAttributes && isAllowAnonymous == false)
            {
                if (operation.Parameters == null)
                {
                    operation.Parameters = new List<IParameter>();
                }
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name = "Authorization",  //添加Authorization头部参数
                    In = "header",
                    Type = "string",
                    Description = "身份验证Authorization，值Bearer+空格+token字符串",
                    Required = false
                });
            }

        }
    }
}